from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update, db_insert
from utilsapp.common import assign_value, parsing_data_id

bluePrint = Blueprint("menum", __name__)
tableName = "menu"


# 分页查询
@bluePrint.route("/getlist", methods=["post"])
def table_list():
    sql = f"""
         SELECT m1.*,m2.name as parent_name,m2.label as parent_label FROM menu m1
 LEFT JOIN menu m2 on m1.parent = m2.id
 WHERE 1=1
    """
    a = request.json
    label = assign_value(a, "label")
    name = assign_value(a, "name")
    type_ = assign_value(a, "type")
    page = assign_value(a, "page", 1)
    size = assign_value(a, "size", 20)
    if label != "":
        sql += f" and m1.label like '%{label}%' "
    if name != "":
        sql += f" and m1.name like '%{name}%' "
    if type_ != "":
        sql += f" and m1.type = {int(type_)} "

    sql = f"select * from ({sql} ) as a order by id "

    return db_pagelist(sql, page, size)


@bluePrint.route("/add", methods=["post"])
def add():
    return db_insert(tableName, request.json)


@bluePrint.route("/delete", methods=["post"])
def a():
    id_ = assign_value(request.json, "id")
    return db_delete(tableName, f"WHERE id = %s", {"id_": id_})


@bluePrint.route("/edit", methods=["post"])
def b():
    id = request.json["id"]
    keys_not_add = ["id", "parent_label", "parent_name"]
    addModel = {
        key: request.json[key] for key in request.json if key not in keys_not_add
    }
    return db_update(tableName, addModel, f"WHERE id=%s", {"id": id})
